using System;
using System.Collections.Generic;
using MSOffice = Microsoft.Office.Core;

namespace Office.Utility.Toolbar
{
    public sealed class Menu : CommandBar
    {
        private readonly List<MenuItem> _listMenuItems = new List<MenuItem>();
        public List<MenuItem> MenuItems
        {
            get { return _listMenuItems; }
        }

        public int? Position { get; set; }

        public Menu(string name)
            : base(name)
        {
        }

        public Menu(string name, CommandBarWindowType windowType)
            : base(name, windowType)
        {
        }

        internal override void Attach(WindowAdapter window)
        {
            //Get the command bars collection from the window. 
            var bars = window.CommandBars;
            if (bars == null)
                throw new ApplicationException("CommandBars property was null");

            //Look for the existance of a commandbar with a matching name already on the window
            //If it's there, delete it
            var menuBar = bars.ActiveMenuBar;
            var menusToDelete = new List<Microsoft.Office.Core.CommandBarPopup>();
            foreach (MSOffice.CommandBarPopup m in menuBar.Controls)
            {
                if (m.Caption == Name)
                    menusToDelete.Add(m);
            }

            foreach (MSOffice.CommandBarButton m in menusToDelete)
                m.Delete(Type.Missing);

            //create the menu
            var menu = (MSOffice.CommandBarPopup)menuBar.Controls.Add(
                MSOffice.MsoControlType.msoControlPopup, 
                Type.Missing, 
                string.Empty,
                Position.HasValue ? Position.Value : Type.Missing,
                true);
            menu.Caption = Name;
            
            //Show and enable the toolbar
            ShowCommandBar(window, menuBar);

            //Attach the toolbar controls to the window command bar
            foreach (var item in MenuItems)
                item.Attach(menu, window, menuBar);

            window.SelectionChange += ((sender, args) => ShowCommandBar(window, menuBar));

            Windows.Add(window);

        }

        internal override void Detach(WindowAdapter window)
        {
            Windows.Remove(window);

            if (window.CommandBars == null) return;
            var menuBar = window.CommandBars.ActiveMenuBar;
            foreach (MSOffice.CommandBarPopup m in menuBar.Controls)
            {
                if (m.Caption == Name)
                {
                    m.Delete(false);
                }
            }
        }

    }
}
